import AsyncStorage from '@/utils/AsyncStorage';
// import { action, toJS, makeAutoObservable } from 'mobx';
import Taro from "@tarojs/taro";
import { IProduct, isNB, isGPRS, isBLE } from '@/config/product';
import { isSameDevice } from '@/utils';
import ScanQrcode from '@/utils/ScanQrcode'
import { IBaseConfigNetworkProps } from './base/baseConfigNetwork';

const wifiInfoSaveKey = 'wifiInfoSaveKey';
const lastestUseWifiName = 'lastestUseWifiName';

interface IWifiInfoProps {
  wifiName: string; // wifi名字

  password: string; // wifi密码

  isManualInput?: boolean; // 是否为手动输入
}

class ConfigWifi {

  wifiName: string | undefined = undefined; // 当前配网wifi名字

  password: string = ''; // 当前配网的wifi密码

  isManualInput: boolean = false;

  productConfig: IProduct | undefined;

  configModel: IBaseConfigNetworkProps | undefined;

  devices: IDevice[] = [];

  notFilterPk = false; // 配网不过滤PK，主要是蓝牙配网使用

  public eventID:string | null = null // 配网监控使用
  public sdkResCache: any = null; // 配网时sdk的返回结果，用于上报
  public curPk: string | null = null;
  public curStartData:any = null;

  // constructor() {
    // this.getLastestUseWifiInfo();
  // }

  updateWifiInfo({ wifiName, password, isManualInput = false }: { wifiName: string, password: string, isManualInput: boolean }) {
    this.wifiName = wifiName;
    this.password = password;
    this.isManualInput = isManualInput;
    AsyncStorage.setItem(lastestUseWifiName, wifiName);
    this.saveWifiInfoToLocal({ wifiName, password, isManualInput });
  }

  goToConfig = (product: IProduct) => {
    if (isNB(product) || isGPRS(product)) {
      // 4G，去扫码
      ScanQrcode()
      return
    } else if (isBLE(product)) {
      // 只是单纯蓝牙的，去蓝牙添加
      Taro.navigateTo({ url: '/pages/configDevice/bleAdd/index' })
      return
    }
    this.updateConfigProduct(product);
    this.notFilterPk = false; // 每次配网都重置这个变量
    Taro.navigateTo({ url: '/pages/configDevice/selectWifi/index' })
  }

  updateConfigProduct(product: IProduct) {
    console.log('updateConfigProduct', product.networkConfigType)
    this.productConfig = product
  }

  updateConfigModel(configModel: IBaseConfigNetworkProps) {
    this.configModel = configModel
  }

  goToCurrentModel() {
    Taro.navigateTo({ url: '/pages/configDevice/loading/index' })
  }

  updateConfigModelAndGo(configModel: IBaseConfigNetworkProps) {
    this.configModel = configModel
    this.goToCurrentModel()
  }

  addDevice(device: IDevice) {
    const index = this.devices.findIndex(i => isSameDevice(i, device));
    if (index < 0) {
      this.devices.push(device);
    }
  }

  getLastestUseWifiInfo = async () => {
    const wifiName = await AsyncStorage.getItem(lastestUseWifiName);
    if (wifiName) {
      const info = await this.getWifiInfoINLocalByWifiName(wifiName);
      this.wifiName = info.wifiName;
      this.password = info.password;
      this.isManualInput = info.isManualInput;
    }
  }

  saveWifiInfoToLocal = async ({ wifiName, password, isManualInput }: IWifiInfoProps) => {
    if (wifiName && password) {
      const info = { wifiName, password, isManualInput: !!isManualInput };
      let localWIfiInfoString = await AsyncStorage.getItem(wifiInfoSaveKey);
      try {
        if (!localWIfiInfoString) {
          localWIfiInfoString = '{}';
        }
        const json = JSON.parse(localWIfiInfoString);
        json[wifiName] = info;
        return AsyncStorage.setItem(wifiInfoSaveKey, JSON.stringify(json));
      } catch (error) {
        console.log('wifi JSON解析错误', error);
        return { success: false };
      }
    }
  }

  getWifiInfoINLocalByWifiName = async (wifiName: string) => {
    let localWIfiInfoString = await AsyncStorage.getItem(wifiInfoSaveKey);
    try {
      if (!localWIfiInfoString) {
        localWIfiInfoString = '{}';
      }
      const json = JSON.parse(localWIfiInfoString);
      return json[wifiName];
    } catch (error) {
      console.log('wifi JSON解析错误', error);
      return undefined;
    }
  }

  setNotFilterPk = () => {
    // 在goToConfig之后调用，可以使蓝牙配网的pk过滤不生效，即全部蓝牙产品都可以配上
    this.notFilterPk = true;
  }

  clearData = () => {
    this.wifiName = undefined;
    this.password = '';
    this.isManualInput = false;
    this.productConfig = undefined;
    this.configModel = undefined;
    this.devices = [];
  }

  // updateDeviceName({ device, name }: { device: IDevice, name: string }) {
  //   const index = this.devices.findIndex(i => isSameDevice(i, device));
  //   if (index < 0) {
  //     this.devices.splice(index, 1, { ...device, name });
  //   }
  // }

}


export default new ConfigWifi();
